import util from '@/utils/util.js';
import host from "@/utils/host.ts";

const request = function(params) {

	return new Promise((resolve, reject) => {

		params = params ? params : {};

		if (params.url.indexOf("weixin") > -1) {
			var url = params.url;
		} else {
			var url = host + (params.url ? params.url : '');
		}

		if (params.load) {
			uni.showLoading({
				title: "加载中",
			})
		}

		params.header = {
			'Content-Type': 'application/x-www-form-urlencoded',
		}

		if (uni.getStorageSync("token")) {
			params.header.token = uni.getStorageSync('token');
		}

		params.dataType = params.dataType ? params.dataType : "json";

		uni.request({
			url: url,
			method: params.method ? params.method : "POST",
			sslVerify: false,
			data: params.data,
			header: params.header,
			dataType: params.dataType,
			success(res) {

				if (params.load) {
					uni.hideLoading()
				}

				if (res.statusCode == 401) {
					util.alert({
						title: "系统提示",
						cancel: false,
						value: "请先登录",
						success() {
							uni.navigateTo({
								url: "/pages/login/login?type=back"
							})
						}
					})
					return;
				}

				//	嵌套式回调
				params.success ? params.success(res.data) : function() {};

				//	链接式回调
				resolve(res.data);

			},
			fail: res => {

				if (params.load) {
					uni.hideLoading()
				}

				//	嵌套式回调
				params.fail ? params.fail(res) : function() {};

				//	
				reject(res)

			}
		})
	})

}

export default request;